#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
MaixCAM Pro MQTT连接示例
连接到指定的MQTT服务器并进行消息订阅和发布
"""

import time
import json
import threading
import base64
import os

# 尝试导入MaixPy模块
try:
    from maix import display, image, camera, app, gpio, pinmap, sys, err, pwm
    MAIX_AVAILABLE = True
except ImportError:
    print("警告: MaixPy模块未找到，某些功能可能不可用")
    MAIX_AVAILABLE = False
    
    # 提供一个简单的app模拟器用于测试
    class AppSimulator:
        def need_exit(self):
            return False
    app = AppSimulator()

# 导入MQTT客户端
try:
    import paho.mqtt.client as mqtt
except ImportError:
    print("错误: 请先安装paho-mqtt库")
    print("安装命令: pip install paho-mqtt")
    exit(1)

# MQTT配置参数
MQTT_BROKER = "82.157.22.162"  # MQTT服务器地址
MQTT_PORT = 8083              # MQTT端口号
MQTT_CLIENT_ID = "maixcam"  # 客户端ID
MQTT_KEEPALIVE = 60           # 保活时间
MQTT_PATH = "/mqtt"            # WebSocket路径

# 主题配置
TOPIC_PUBLISH = "maixcam_data"     # 发布主题
TOPIC_SUBSCRIBE = "maixcam_cmd"    # 订阅主题

class MQTTClient:
    def __init__(self):
        self.client = None
        self.connected = False
        self.message_count = 0
        self.flash_led = None
        self.camera = None
        self.init_flash_led()
        
        # PWM电机控制初始化
        self.motor_pwms = {}
        self.init_camera_motors()
        
        # 初始化相机
        self.init_camera()
        
    def init_flash_led(self):
        """初始化闪光灯（照明 LED）"""
        if not MAIX_AVAILABLE:
            print("⚠️ MaixPy模块不可用，无法控制LED")
            return
            
        try:
            # 根据设备类型设置引脚（MaixCAM Pro的照明LED连接到B3引脚）
            pin_name = "B3"  # MaixCAM Pro的照明LED引脚
            gpio_name = "GPIOB3"
            
            # 设置引脚功能为GPIO
            err.check_raise(pinmap.set_pin_function(pin_name, gpio_name), "set pin failed")
            
            # 初始化GPIO为输出模式
            self.flash_led = gpio.GPIO(gpio_name, gpio.Mode.OUT)
            self.flash_led.value(0)  # 初始状态为关闭
            
            print("✓ 照明LED初始化成功")
            
        except Exception as e:
            print(f"⚠️ LED初始化失败: {e}")
            self.flash_led = None
    
    def init_camera_motors(self):
        """初始化摄像头云台电机控制(2个电机，每个用2个引脚控制)"""
        if not MAIX_AVAILABLE:
            print("⚠️ MaixPy模块不可用，无法控制PWM")
            return
            
        try:
            # 2个电机配置：每个电机需2个引脚控制方向
            motor_config = {
                "vertical": {     # 垂直电机 - A19和A18控制
                    "pin1": "A19",   # PWM7
                    "pin2": "A18",   # PWM6
                    "pwm1": 7,
                    "pwm2": 6
                },
                "horizontal": {   # 水平电机 - 使用A16和A17控制
                    "pin1": "A16",    # PWM4
                    "pin2": "A17",    # PWM5
                    "pwm1": 4,
                    "pwm2": 5
                }
            }
            
            # 初始化所有PWM通道
            for motor_name, config in motor_config.items():
                try:
                    # 初始化第一个引脚
                    pin1 = config["pin1"]
                    pwm1 = config["pwm1"]
                    print(f"  正在初始化 {pin1} -> PWM{pwm1}...")
                    err.check_raise(pinmap.set_pin_function(pin1, f"PWM{pwm1}"), 
                                   f"set {pin1} to PWM{pwm1} failed")
                    pwm_obj1 = pwm.PWM(pwm1, freq=1000, duty=0, enable=True)
                    self.motor_pwms[f"{motor_name}_pin1"] = pwm_obj1
                    
                    # 初始化第二个引脚
                    pin2 = config["pin2"]
                    pwm2 = config["pwm2"]
                    print(f"  正在初始化 {pin2} -> PWM{pwm2}...")
                    err.check_raise(pinmap.set_pin_function(pin2, f"PWM{pwm2}"), 
                                   f"set {pin2} to PWM{pwm2} failed")
                    pwm_obj2 = pwm.PWM(pwm2, freq=1000, duty=0, enable=True)
                    self.motor_pwms[f"{motor_name}_pin2"] = pwm_obj2
                    
                    print(f"✓ {motor_name}电机: {pin1}(PWM{pwm1}) + {pin2}(PWM{pwm2}) 初始化成功")
                    
                except Exception as motor_error:
                    print(f"⚠️ {motor_name}电机初始化失败: {motor_error}")
                    if motor_name == "horizontal":
                        print("  提示: 尝试使用简化配置（只用A19和A18）")
                        # 简化配置：只使用垂直电机的引脚
                        self.init_simple_motor_config()
                        return
            
            print("✓ 摄像头云台电机控制初始化完成")
            print("  - 垂直电机: A19(PWM7) + A18(PWM6)")
            print("  - 水平电机: A16(PWM4) + A17(PWM5)")
            
            # 启动时进行电机自检
            self.motor_self_test()
            
        except Exception as e:
            print(f"⚠️ 电机初始化失败: {e}")
            print("  尝试使用简化配置...")
            self.init_simple_motor_config()
    
    def init_simple_motor_config(self):
        """简化的电机配置 - 只使用A19和A18两个引脚"""
        try:
            print("ℹ️ 使用简化配置: 只初始化A19和A18引脚")
            
            # 初始化A19 (PWM7)
            print("  正在初始化 A19 -> PWM7...")
            err.check_raise(pinmap.set_pin_function("A19", "PWM7"), "set A19 to PWM7 failed")
            pwm_obj1 = pwm.PWM(7, freq=1000, duty=0, enable=True)
            self.motor_pwms["vertical_pin1"] = pwm_obj1
            
            # 初始化A18 (PWM6)
            print("  正在初始化 A18 -> PWM6...")
            err.check_raise(pinmap.set_pin_function("A18", "PWM6"), "set A18 to PWM6 failed")
            pwm_obj2 = pwm.PWM(6, freq=1000, duty=0, enable=True)
            self.motor_pwms["vertical_pin2"] = pwm_obj2
            
            print("✓ 简化配置初始化成功")
            print("  - A19(PWM7) + A18(PWM6) 可用")
            print("  - 注意: 水平控制不可用，只能使用垂直控制")
            
        except Exception as e:
            print(f"❌ 简化配置也失败: {e}")
            print("  请检查:")
            print("  1. MaixPy环境是否正常")
            print("  2. A19和A18引脚是否可用")
            print("  3. PWM6和PWM7通道是否支持")
            self.motor_pwms = {}
    
    def init_camera(self):
        """初始化相机"""
        if not MAIX_AVAILABLE:
            print("⚠️ MaixPy模块不可用，无法初始化相机")
            return
            
        try:
            # 初始化相机 - 使用640x480分辨率，适合MQTT传输
            self.camera = camera.Camera(640, 480, image.Format.FMT_RGB888)
            print("✅ 相机初始化成功 (640x480)")
            print("   - 支持拍照功能")
            print("   - 支持MQTT图片传输")
            
        except Exception as e:
            print(f"⚠️ 相机初始化失败: {e}")
            self.camera = None
    
    def capture_photo(self, filename=None):
        """拍照并保存
        
        Args:
            filename: 保存的文件名，如果为None则自动生成时间戳文件名
            
        Returns:
            tuple: (success, filepath, error_message)
        """
        if not MAIX_AVAILABLE or self.camera is None:
            return False, None, "相机不可用"
            
        try:
            # 拍照
            img = self.camera.read()
            if img is None:
                return False, None, "拍照失败，未获取到图像"
            
            # 生成文件名
            if filename is None:
                timestamp = time.strftime("%Y%m%d_%H%M%S", time.localtime())
                filename = f"photo_{timestamp}.jpg"
            
            # 确保文件名以.jpg结尾
            if not filename.lower().endswith(('.jpg', '.jpeg')):
                filename += '.jpg'
            
            # 保存路径 - 使用/tmp目录（临时文件）
            filepath = f"/tmp/{filename}"
            
            # 保存图片
            img.save(filepath)
            
            print(f"📸 拍照成功: {filepath}")
            print(f"   分辨率: {img.width()}x{img.height()}")
            
            return True, filepath, None
            
        except Exception as e:
            error_msg = f"拍照过程出错: {e}"
            print(f"❌ {error_msg}")
            return False, None, error_msg
    
    def image_to_base64(self, filepath):
        """将图片文件转换为base64编码
        
        Args:
            filepath: 图片文件路径
            
        Returns:
            tuple: (success, base64_string, error_message)
        """
        try:
            if not os.path.exists(filepath):
                return False, None, f"文件不存在: {filepath}"
            
            with open(filepath, 'rb') as f:
                image_data = f.read()
                base64_string = base64.b64encode(image_data).decode('utf-8')
                
            print(f"🔄 图片转换为base64成功，大小: {len(base64_string)} 字符")
            return True, base64_string, None
            
        except Exception as e:
            error_msg = f"图片转换失败: {e}"
            print(f"❌ {error_msg}")
            return False, None, error_msg
    
    def send_photo_via_mqtt(self, filename=None, delete_after_send=True):
        """拍照并通过MQTT发送
        
        Args:
            filename: 保存的文件名
            delete_after_send: 发送后是否删除临时文件
            
        Returns:
            bool: 是否成功
        """
        try:
            # 拍照
            success, filepath, error = self.capture_photo(filename)
            if not success:
                print(f"❌ 拍照失败: {error}")
                return False
            
            # 转换为base64
            success, base64_data, error = self.image_to_base64(filepath)
            if not success:
                print(f"❌ 图片转换失败: {error}")
                return False
            
            # 构建MQTT消息
            photo_data = {
                "type": "photo",
                "timestamp": int(time.time()),
                "filename": os.path.basename(filepath),
                "size": len(base64_data),
                "format": "jpeg",
                "resolution": "640x480",
                "data": base64_data
            }
            
            # 发送MQTT消息
            message = json.dumps(photo_data, ensure_ascii=False)
            success = self.publish_message(message, qos=1)  # 使用QoS 1确保送达
            
            if success:
                print(f"📤 照片通过MQTT发送成功")
                print(f"   文件名: {os.path.basename(filepath)}")
                print(f"   大小: {len(base64_data)} 字符")
            else:
                print(f"❌ MQTT发送失败")
            
            # 清理临时文件
            if delete_after_send:
                try:
                    os.remove(filepath)
                    print(f"🗑️ 临时文件已删除: {filepath}")
                except:
                    pass
            
            return success
            
        except Exception as e:
            print(f"❌ 发送照片过程出错: {e}")
            return False
    
    def motor_self_test(self):
        """电机自检 - 启动时让所有方向都运行1秒"""
        if not self.motor_pwms:
            print("⚠️ 电机不可用，跳过自检")
            return
            
        print("\n🔧 开始电机自检...")
        
        try:
            # 自检顺序：上 -> 下 -> 左 -> 右
            test_directions = ["up", "down", "left", "right"]
            
            for direction in test_directions:
                print(f"  🎯 自检 {direction} 方向...")
                
                if direction == "up":
                    self.motor_pwms["vertical_pin1"].duty(100)  # A19 高
                    self.motor_pwms["vertical_pin2"].duty(0)    # A18 低
                    print("    ✓ A19=高电平, A18=低电平")
                    
                elif direction == "down":
                    self.motor_pwms["vertical_pin1"].duty(0)    # A19 低
                    self.motor_pwms["vertical_pin2"].duty(100)  # A18 高
                    print("    ✓ A19=低电平, A18=高电平")
                    
                elif direction == "left":
                    self.motor_pwms["horizontal_pin1"].duty(100) # A16 高
                    self.motor_pwms["horizontal_pin2"].duty(0)   # A17 低
                    print("    ✓ A16=高电平, A17=低电平")
                    
                elif direction == "right":
                    self.motor_pwms["horizontal_pin1"].duty(0)   # A16 低
                    self.motor_pwms["horizontal_pin2"].duty(100) # A17 高
                    print("    ✓ A16=低电平, A17=高电平")
                
                # 运行0.2秒
                time.sleep(0.2)
                
                # 停止当前电机
                for pwm_obj in self.motor_pwms.values():
                    pwm_obj.duty(0)
                    
                print(f"    ✓ {direction} 方向自检完成")
                
                # 各方向之间间隔0.5秒
                time.sleep(0.5)
                
            print("✅ 电机自检完成，所有方向运行正常！\n")
            
        except Exception as e:
            print(f"❌ 电机自检失败: {e}")
            # 确保所有电机停止
            try:
                for pwm_obj in self.motor_pwms.values():
                    pwm_obj.duty(0)
            except:
                pass
    
    def flash_led_for_duration(self, duration=1.0):
        """闪烁LED指定时间"""
        if self.flash_led is None:
            print("⚠️ LED不可用，无法闪烁")
            return
            
        def flash_thread():
            try:
                print(f"💡 开始闪烁LED {duration}秒")
                # 打开LED
                self.flash_led.value(1)
                time.sleep(duration)
                # 关闭LED
                self.flash_led.value(0)
                print(f"💡 LED闪烁结束")
            except Exception as e:
                print(f"⚠️ LED闪烁错误: {e}")
        
        # 在单独线程中执行，避免阻塞MQTT循环
        thread = threading.Thread(target=flash_thread, daemon=True)
        thread.start()
    
    def turn_off_led(self):
        """关闭LED"""
        if self.flash_led is None:
            print("⚠️ LED不可用")
            return
            
        try:
            self.flash_led.value(0)
            print(f"💡 LED已关闭")
        except Exception as e:
            print(f"⚠️ 关闭LED错误: {e}")
    
    def move_camera(self, direction, duration=0.5):
        """控制摄像头云台移动(2个电机，每个电机2个引脚控制方向)
        
        Args:
            direction: 方向 ('up', 'down', 'left', 'right')
            duration: 电机运行持续时间(秒)，默认0.5秒
        """
        if not self.motor_pwms:
            print("⚠️ 电机控制不可用，无法控制摄像头")
            return
            
        def move_thread():
            try:
                print(f"🎥 摄像头向 {direction} 移动 {duration}秒")
                
                # 根据方向设置对应的PWM高低电平组合
                if direction == "up":
                    # 向上: A19(高) + A18(低)
                    if "vertical_pin1" in self.motor_pwms and "vertical_pin2" in self.motor_pwms:
                        self.motor_pwms["vertical_pin1"].duty(100)  # A19 高电平
                        self.motor_pwms["vertical_pin2"].duty(0)    # A18 低电平
                        print("✓ A19=高电平, A18=低电平")
                    else:
                        print("⚠️ 垂直电机不可用")
                        return
                        
                elif direction == "down":
                    # 向下: A19(低) + A18(高)
                    if "vertical_pin1" in self.motor_pwms and "vertical_pin2" in self.motor_pwms:
                        self.motor_pwms["vertical_pin1"].duty(0)    # A19 低电平
                        self.motor_pwms["vertical_pin2"].duty(100)  # A18 高电平
                        print("✓ A19=低电平, A18=高电平")
                    else:
                        print("⚠️ 垂直电机不可用")
                        return
                        
                elif direction == "left":
                    # 向左: A16(高) + A17(低)
                    if "horizontal_pin1" in self.motor_pwms and "horizontal_pin2" in self.motor_pwms:
                        self.motor_pwms["horizontal_pin1"].duty(100)  # A16 高电平
                        self.motor_pwms["horizontal_pin2"].duty(0)    # A17 低电平
                        print("✓ A16=高电平, A17=低电平")
                    else:
                        print("⚠️ 水平电机不可用")
                        return
                        
                elif direction == "right":
                    # 向右: A16(低) + A17(高)
                    if "horizontal_pin1" in self.motor_pwms and "horizontal_pin2" in self.motor_pwms:
                        self.motor_pwms["horizontal_pin1"].duty(0)    # A16 低电平
                        self.motor_pwms["horizontal_pin2"].duty(100)  # A17 高电平
                        print("✓ A16=低电平, A17=高电平")
                    else:
                        print("⚠️ 水平电机不可用")
                        return
                else:
                    print(f"⚠️ 未知方向: {direction}")
                    return
                
                # 等待指定时间
                time.sleep(duration)
                
                # 停止电机 - 所有PWM设置为低电平
                for motor_name, pwm_obj in self.motor_pwms.items():
                    pwm_obj.duty(0)
                    
                print(f"✓ 摄像头 {direction} 移动完成，所有电机已停止")
                
            except Exception as e:
                print(f"⚠️ 摄像头移动错误: {e}")
                # 错误时也要停止所有电机
                try:
                    for pwm_obj in self.motor_pwms.values():
                        pwm_obj.duty(0)
                except:
                    pass
        
        # 在单独线程中执行，避免阻塞MQTT循环
        thread = threading.Thread(target=move_thread, daemon=True)
        thread.start()
        
    def on_connect(self, client, userdata, flags, rc):
        """连接回调函数"""
        if rc == 0:
            print(f"✓ MQTT连接成功! 结果代码: {rc}")
            self.connected = True
            # 订阅主题（使用QoS 1确保接收到指令）
            client.subscribe(TOPIC_SUBSCRIBE, qos=1)
            print(f"✓ 已订阅主题: {TOPIC_SUBSCRIBE} (QoS=1)")
        else:
            print(f"✗ MQTT连接失败! 结果代码: {rc}")
            self.connected = False
    
    def on_disconnect(self, client, userdata, rc):
        """断开连接回调函数"""
        print(f"! MQTT连接断开! 结果代码: {rc}")
        self.connected = False
    
    def on_message(self, client, userdata, msg):
        """消息接收回调函数"""
        try:
            topic = msg.topic
            payload = msg.payload.decode('utf-8')
            print(f"📩 收到消息:")
            print(f"   主题: {topic}")
            print(f"   内容: {payload}")
            
            # 处理接收到的命令
            self.handle_command(payload)
            
        except Exception as e:
            print(f"✗ 处理消息时出错: {e}")
    
    def on_publish(self, client, userdata, mid):
        """消息发布回调函数"""
        print(f"✓ 消息发布成功! 消息ID: {mid}")
    
    def handle_command(self, command):
        """处理接收到的命令"""
        try:
            if command.startswith("{"):
                # JSON格式命令
                cmd_data = json.loads(command)
                cmd_type = cmd_data.get("type", "unknown")
                print(f"📋 执行命令类型: {cmd_type}")
                
                if cmd_type == "status":
                    # 返回设备状态
                    self.publish_status()
                elif cmd_type == "led":
                    # 控制LED
                    state = cmd_data.get("state", "on")
                    duration = cmd_data.get("duration", 1.0)  # 默认1秒
                    print(f"💡 LED控制: {state}, 持续时间: {duration}秒")
                    
                    if state == "flash" or state == "on":
                        self.flash_led_for_duration(duration)
                    elif state == "off":
                        self.turn_off_led()
                        
                elif cmd_type == "camera":
                    # 控制摄像头云台
                    direction = cmd_data.get("direction", "")
                    time_duration = cmd_data.get("time", 0.5)  # 默认0.5秒PWM高电平
                    print(f"🎥 摄像头控制: {direction}, 持续时间: {time_duration}秒")
                    
                    if direction in ["up", "down", "left", "right"]:
                        self.move_camera(direction, time_duration)
                    else:
                        print(f"⚠️ 无效的摄像头方向: {direction}")
                        
                elif cmd_type == "photo":
                    # 拍照命令
                    filename = cmd_data.get("filename", None)
                    send_via_mqtt = cmd_data.get("send", True)  # 默认通过MQTT发送
                    print(f"📸 拍照命令: filename={filename}, send_via_mqtt={send_via_mqtt}")
                    
                    if send_via_mqtt:
                        # 拍照并通过MQTT发送
                        self.send_photo_via_mqtt(filename)
                    else:
                        # 只拍照，不发送
                        success, filepath, error = self.capture_photo(filename)
                        if success:
                            print(f"✅ 拍照成功，已保存到: {filepath}")
                        else:
                            print(f"❌ 拍照失败: {error}")
                    
            else:
                # 文本命令
                if command.lower() == "ping":
                    self.publish_message("pong")
                elif command.lower() == "status":
                    self.publish_status()
                else:
                    print(f"❓ 未知命令: {command}")
                    
        except Exception as e:
            print(f"✗ 命令处理错误: {e}")
    
    def connect(self):
        """连接到MQTT服务器"""
        try:
            print("🔗 正在连接MQTT服务器...")
            print(f"   服务器: {MQTT_BROKER}:{MQTT_PORT}")
            print(f"   客户端ID: {MQTT_CLIENT_ID}")
            
            # 创建MQTT客户端（使用WebSocket传输）
            self.client = mqtt.Client(client_id=MQTT_CLIENT_ID, clean_session=True, transport="websockets")
            
            # 设置回调函数
            self.client.on_connect = self.on_connect
            self.client.on_disconnect = self.on_disconnect
            self.client.on_message = self.on_message
            self.client.on_publish = self.on_publish
            
            # 如果需要用户名和密码，可以在这里设置
            # self.client.username_pw_set("username", "password")
            
            # 设置WebSocket路径
            self.client.ws_set_options(path=MQTT_PATH)
            
            # 连接到服务器
            self.client.connect(MQTT_BROKER, MQTT_PORT, MQTT_KEEPALIVE)
            
            # 启动网络循环
            self.client.loop_start()
            
            # 等待连接完成
            for i in range(10):
                if self.connected:
                    break
                time.sleep(1)
                print(f"   等待连接... ({i+1}/10)")
            
            if not self.connected:
                print("✗ 连接超时")
                return False
                
            return True
            
        except Exception as e:
            print(f"✗ 连接失败: {e}")
            return False
    
    def disconnect(self):
        """断开MQTT连接"""
        if self.client:
            self.client.loop_stop()
            self.client.disconnect()
            print("🔌 MQTT连接已断开")
    
    def publish_message(self, message, topic=None, qos=1):
        """发布消息（默认使用QoS 1保证送达）"""
        if not self.connected or self.client is None:
            print("✗ MQTT未连接，无法发布消息")
            return False
            
        try:
            if topic is None:
                topic = TOPIC_PUBLISH
                
            result = self.client.publish(topic, message, qos=qos)
            if result.rc == mqtt.MQTT_ERR_SUCCESS:
                print(f"📤 发布消息到 {topic} (QoS={qos}): {message}")
                return True
            else:
                print(f"✗ 消息发布失败: {result.rc}")
                return False
                
        except Exception as e:
            print(f"✗ 发布消息时出错: {e}")
            return False
    
    def publish_status(self):
        """发布设备状态"""
        status_data = {
            "device": "MaixCAM Pro",
            "client_id": MQTT_CLIENT_ID,
            "timestamp": int(time.time()),
            "connected": self.connected,
            "message_count": self.message_count,
            "uptime": int(time.time())  # 简化的运行时间
        }
        
        self.publish_message(json.dumps(status_data, ensure_ascii=False))
    
    def publish_sensor_data(self, data):
        """发布传感器数据"""
        sensor_data = {
            "type": "sensor",
            "timestamp": int(time.time()),
            "data": data
        }
        
        self.publish_message(json.dumps(sensor_data, ensure_ascii=False))

def main():
    """主函数"""
    print("=" * 50)
    print("🚀 MaixCAM Pro MQTT客户端启动")
    print("=" * 50)
    
    # 创建MQTT客户端
    mqtt_client = MQTTClient()
    
    try:
        # 连接到MQTT服务器
        if not mqtt_client.connect():
            print("❌ MQTT连接失败，程序退出")
            return
        
        print("\n✅ MQTT客户端运行中...")
        print("📝 使用说明:")
        print(f"   - 发布主题: {TOPIC_PUBLISH}")
        print(f"   - 订阅主题: {TOPIC_SUBSCRIBE}")
        print("   - 支持命令: ping, status, LED控制等")
        print("   - 按Ctrl+C退出\n")
        
        # 发布初始状态
        mqtt_client.publish_status()
        
        # 主循环
        last_heartbeat = time.time()
        heartbeat_interval = 30  # 30秒发送一次心跳
        
        while not app.need_exit():
            current_time = time.time()
            
            # 定期发送心跳
            if current_time - last_heartbeat >= heartbeat_interval:
                heartbeat_data = {
                    "type": "heartbeat",
                    "timestamp": int(current_time),
                    "device": "MaixCAM Pro"
                }
                mqtt_client.publish_message(json.dumps(heartbeat_data, ensure_ascii=False))
                last_heartbeat = current_time
                print(f"💓 发送心跳 - {time.strftime('%H:%M:%S', time.localtime())}")
            
            # 可以在这里添加其他业务逻辑
            # 比如读取传感器数据、处理摄像头图像等
            
            time.sleep(1)
            
    except KeyboardInterrupt:
        print("\n⚠️ 接收到退出信号")
    except Exception as e:
        print(f"❌ 程序运行错误: {e}")
    finally:
        # 清理资源
        mqtt_client.disconnect()
        print("👋 程序结束")

if __name__ == "__main__":
    main()